import { BTNode } from "../BTNode";
import { BTState } from "../BTState";
import { IConditional } from "../IConditional";
import { BTDecorator } from "./BTDecorator";

/**
 * [行为树]条件节点
 */
export class BTConditional<T = any> extends BTDecorator<T> implements IConditional<T> {

    readonly discriminator: "IConditional";

    /** 当前检测节点状态 */
    condState = BTState.init;

    constructor(
        public condition: IConditional<T>,
        /** 子节点 */
        child: BTNode<T>,
        public shouldReevaluate: boolean
    ) {
        super(child);
    }

    process(ctx: T): BTState {
        this.condState = this.executeConditional(ctx);

        if (this.condState == BTState.succ) {
            return this.child.tick(ctx);
        }

        return BTState.fail;
    }

    done(): void {
        super.done();
        this.condState = BTState.init;
    }

    /**
     * 在shouldReevaluate标志之后执行条件，或者用一个选项来强制更新。
     * 终止将强制更新，以确保他们在条件变化时得到适当的数据。
     */
    executeConditional(context: T, forceUpdate: boolean = false): BTState {
        if (forceUpdate || this.shouldReevaluate || this.condState == BTState.init)
            this.condState = this.condition.process(context);

        return this.condState;
    }


}